<template>
  <div class="main-container">
    <!-- 导航栏 -->
    <nav class="navbar">
      <div class="navbar-container">
        <div class="logo" @click="goToHome">QingBook</div>
        <ul class="nav-menu">
          <li class="nav-item" :class="{ active: activeIndex === 1 }" @click="goToHome">首页</li>
          <li class="nav-item" :class="{ active: activeIndex === 2 }" @click="goToOrders">订单</li>
          <li class="nav-item" :class="{ active: activeIndex === 3 }" @click="goToCart">购物车</li>
          <li class="nav-item">
            <img class="avatar" :src="user.avatarUrl" alt="用户头像" />
          </li>
        </ul>
      </div>
    </nav>

    <!-- 内容区 -->
    <div class="content-wrapper">
      <!-- 轮播图（已替换为指定三张网络图片） -->
      <div class="carousel-section">
        <div class="custom-carousel-container">
          <div class="custom-carousel">
            <div
              class="custom-carousel-item"
              v-for="(url, index) in imgList"
              :key="index"
              :class="{ active: currentIndex === index }"
              :style="{
                transform: getItemTransform(index),
                zIndex: getItemZIndex(index),
                opacity: getItemOpacity(index)
              }"
              @click="handleItemClick(index)"
            >
              <img :src="url" class="carousel-image" alt="轮播图" />
            </div>
          </div>
          <div class="carousel-indicators">
            <span
              v-for="(_, index) in imgList"
              :key="'indicator-' + index"
              :class="{ active: currentIndex === index }"
              @click="setCurrentIndex(index)"
            ></span>
          </div>
        </div>
      </div>

      <!-- 商品展示 -->
      <div class="products-section">
        <h2 class="section-title">青友推荐</h2>

        <!-- 加载 -->
        <div v-if="isLoading" class="loading">
          <div class="spinner"></div>
          <p>正在加载商品...</p>
        </div>

        <!-- 错误 -->
        <div v-else-if="error" class="error">
          <i class="fas fa-exclamation-circle"></i>
          <p>{{ error }}</p>
          <button class="retry-btn" @click="productStore.fetchProducts">重试</button>
        </div>

        <!-- 商品列表 -->
        <div v-else class="product-grid">
          <div class="product-card" v-for="product in products" :key="product.id">
            <div class="product-image">
              <span class="product-tag">{{ product.tag || '新品' }}</span>
              <img
                :src="product.coverUrl"
                :alt="product.name"
                class="product-img"
                @error="handleImageError(product)"
              />
            </div>
            <div class="product-info">
              <h3 class="product-title">{{ product.name }}</h3>
              <p class="product-desc">{{ product.description }}</p>
              <div class="product-price">
                <div class="price-container">
                  <span class="price">¥{{ product.price.toFixed(2) }}</span>
                  <span class="original-price" v-if="product.originalPrice">
                    ¥{{ product.originalPrice.toFixed(2) }}
                  </span>
                </div>
                <button
                  class="buy-btn"
                  @click="addToCart(product)"
                  :disabled="product.available === false"
                >
                  <i class="fas fa-cart-plus"></i> 购买
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/store/auth'
import { useProductStore } from '@/store/products'
import type { Product } from '@/types/product'

/* 导航 */
const authStore = useAuthStore()
const user = ref(authStore.user || { name: '用户', username: 'username', avatarUrl: 'src/assets/header.png' })
const router = useRouter()
const activeIndex = ref(1)
const goToHome  = () => { activeIndex.value = 1; router.push('/shop') }
const goToOrders = () => { activeIndex.value = 2; router.push('/shoporder') }
const goToCart   = () => { activeIndex.value = 3; router.push('/shopcart') }

/* 轮播图：仅替换图片地址 */
const imgList = [
  'https://img.cdn1.vip/i/68d68f147718d_1758891796.webp',
  'https://img.cdn1.vip/i/68d68f0f76c2c_1758891791.webp',
  'https://img.cdn1.vip/i/68d68f0dc5152_1758891789.jpeg'
]
const currentIndex = ref(0)
const interval = 4000
let timer: number | null = null

const getItemTransform = (index: number) => {
  const diff = index - currentIndex.value
  if (diff === 0) return 'translateX(0) scale(1)'
  if (Math.abs(diff) > 1) return 'translateX(0) scale(0)'
  return `translateX(${diff * 40}%) scale(0.8)`
}
const getItemZIndex = (index: number) => 10 - Math.abs(index - currentIndex.value)
const getItemOpacity = (index: number) => (Math.abs(index - currentIndex.value) > 1 ? 0 : 1)
const setCurrentIndex = (index: number) => { currentIndex.value = index }
const handleItemClick = (index: number) => setCurrentIndex(index)

const startTimer = () => {
  timer = window.setInterval(() => {
    currentIndex.value = (currentIndex.value + 1) % imgList.length
  }, interval)
}
const pauseTimer = () => { if (timer) clearInterval(timer) }

onMounted(startTimer)
onBeforeUnmount(pauseTimer)

/* 商品数据 */
const productStore = useProductStore()
const { products, isLoading, error } = storeToRefs(productStore)
onMounted(() => productStore.fetchProducts())

/* 购物车 */
const addToCart = (product: Product) => {
  if (product.available === false) return
  const cart = JSON.parse(localStorage.getItem('qingbook-cart') || '[]')
  const exist = cart.find((i: any) => i.id === product.id)
  if (exist) exist.quantity += 1
  else cart.push({ id: product.id, title: product.name, image: product.coverUrl, specs: product.description, color: '默认', price: product.price, originalPrice: product.originalPrice || null, quantity: 1, selected: true })
  localStorage.setItem('qingbook-cart', JSON.stringify(cart))
  alert(`已将 ${product.name} 加入购物车`)
}

/* 图片出错 */
const handleImageError = (product: Product) =>
  console.warn(`商品 ${product.name} 图片加载失败`)
</script>

<style scoped>
/* 全局基础 */
* { margin: 0; padding: 0; box-sizing: border-box; font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif; }
.main-container { display: flex; flex-direction: column; min-height: 100vh; }

/* 导航栏 */
.navbar { background: #fff; box-shadow: 0 2px 4px rgba(0,0,0,.1); padding: 0 20px; position: sticky; top: 0; z-index: 100; }
.navbar-container { display: flex; align-items: center; max-width: 1400px; margin: 0 auto; height: 60px; }
.logo { font-size: 20px; font-weight: bold; color: #00b4ac; margin-right: auto; padding: 0 15px; cursor: pointer; user-select: none; }
.nav-menu { display: flex; list-style: none; height: 100%; }
.nav-item { display: flex; align-items: center; padding: 0 15px; cursor: pointer; height: 100%; transition: all .3s; position: relative; }
.nav-item:hover { color: #00b4ac; background: rgba(0,180,172,.1); }
.nav-item.active { color: #00b4ac; border-bottom: 2px solid #00b4ac; }
.avatar { width: 40px; height: 40px; border-radius: 50%; object-fit: cover; }

/* 内容区 */
.content-wrapper { flex: 1; display: flex; flex-direction: column; max-width: 1400px; width: 100%; margin: 0 auto; padding: 30px 20px; }

/* 轮播图 */
.carousel-section { margin: 10px 0 40px; }
.custom-carousel-container { width: 100%; position: relative; margin: 0 auto; }
.custom-carousel { position: relative; width: 100%; height: 350px; overflow: hidden; display: flex; justify-content: center; align-items: center; border-radius: 12px; box-shadow: 0 6px 20px rgba(0,0,0,.1); }
.custom-carousel-item { position: absolute; width: 70%; height: 100%; transition: all .5s; cursor: pointer; border-radius: 12px; overflow: hidden; }
.carousel-image { width: 100%; height: 100%; object-fit: cover; }
.carousel-indicators { position: absolute; bottom: 20px; left: 0; right: 0; display: flex; justify-content: center; gap: 12px; }
.carousel-indicators span { width: 10px; height: 10px; border-radius: 50%; background: rgba(255,255,255,.6); cursor: pointer; transition: all .3s; }
.carousel-indicators span.active { width: 20px; border-radius: 5px; background: #00b4ac; }

/* 商品区 */
.products-section { margin-top: 30px; }
.section-title { font-size: 24px; font-weight: bold; margin-bottom: 25px; color: #333; padding-bottom: 15px; border-bottom: 2px solid #00b4ac; }
.product-grid { display: grid; grid-template-columns: repeat(auto-fill,minmax(280px,1fr)); gap: 20px; margin-bottom: 40px; }
.product-card { background: #fff; border-radius: 10px; overflow: hidden; box-shadow: 0 3px 10px rgba(0,0,0,.08); transition: transform .3s,box-shadow .3s; border: 1px solid #eee; }
.product-card:hover { transform: translateY(-5px); box-shadow: 0 8px 20px rgba(0,0,0,.12); }
.product-image { height: 180px; background: #f9f9f9; display: flex; align-items: center; justify-content: center; color: #999; font-size: 14px; position: relative; overflow: hidden; }
.product-tag { position: absolute; top: 10px; left: 10px; background: #ff6b6b; color: #fff; padding: 4px 10px; border-radius: 15px; font-size: 12px; font-weight: bold; }
.product-img { width: 100%; height: 100%; object-fit: cover; }
.product-info { padding: 15px; }
.product-title { font-size: 14px; font-weight: 600; margin-bottom: 8px; height: 40px; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
.product-desc { font-size: 12px; color: #666; margin-bottom: 10px; height: 36px; overflow: hidden; }
.product-price { display: flex; align-items: center; justify-content: space-between; }
.price { color: #ff6b6b; font-weight: bold; font-size: 18px; }
.original-price { color: #999; font-size: 14px; text-decoration: line-through; }
.buy-btn { background: #00b4ac; color: #fff; border: none; padding: 6px 12px; border-radius: 4px; font-size: 14px; cursor: pointer; transition: background .3s; }
.buy-btn:hover:not(:disabled) { background: #00857d; }
.buy-btn:disabled { opacity: .6; cursor: not-allowed; }

/* 加载 & 错误 */
.loading { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 300px; color: #666; }
.spinner { width: 50px; height: 50px; border: 5px solid #f3f3f3; border-top: 5px solid #00b4ac; border-radius: 50%; animation: spin 1s linear infinite; margin-bottom: 15px; }
@keyframes spin { 0% { transform: rotate(0); } 100% { transform: rotate(360deg); } }
.error { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 300px; color: #ff6b6b; gap: 15px; }
.error i { font-size: 48px; }
.retry-btn { padding: 8px 16px; background: #00b4ac; color: #fff; border: none; border-radius: 4px; cursor: pointer; transition: background .3s; }
.retry-btn:hover { background: #00857d; }

/* 响应式 */
@media (max-width: 768px) {
  .product-grid { grid-template-columns: repeat(auto-fit,minmax(250px,1fr)); gap: 16px; }
  .navbar-container { flex-direction: column; height: auto; padding: 10px 0; }
  .logo { margin-bottom: 10px; }
  .nav-menu { width: 100%; justify-content: space-around; }
  .nav-item { padding: 10px; }
}
</style>